package com.lining.orangeservice.controller;

import com.lining.orangeservice.common.Result;
import com.lining.orangeservice.entity.dto.request.LoginRequest;
import com.lining.orangeservice.entity.dto.LoginResponse;
import com.lining.orangeservice.entity.dto.request.RegisterRequest;
import com.lining.orangeservice.entity.po.User;
import com.lining.orangeservice.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Slf4j
@Tag(name = "认证接口", description = "用户登录、注册、登出等相关接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @Operation(summary = "用户登录", description = "用户通过用户名和密码进行登录认证")
    @PostMapping("/login")
    public Result<LoginResponse> login(@Parameter(description = "登录请求参数") @Validated @RequestBody LoginRequest loginRequest,
                                       HttpServletRequest request) {
        log.info("收到用户登录请求，用户名: {}", loginRequest.getUsername());

        // 验证验证码
        //验证码的生成和存储过程
        //验证码生成：
        //当用户访问登录或注册页面时，前端会向 /captcha/get 接口发送请求获取验证码
        //CaptchaController.getCaptcha() 方法会被调用
        //验证码存储到 Session： 在 CaptchaController 的 getCaptcha 方法中
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("captcha_code");
        String captchaCode = loginRequest.getCaptchaCode();

        if (sessionCode == null || !sessionCode.equalsIgnoreCase(captchaCode)) {
            log.warn("登录失败，验证码错误，用户名: {}", loginRequest.getUsername());
            return Result.error(400, "验证码错误");
        }

        // 验证通过后移除验证码
        session.removeAttribute("captcha_code");

        LoginResponse response = authService.login(loginRequest);
        log.info("用户登录请求处理成功，用户名: {}", loginRequest.getUsername());
        return Result.success(response);
    }

    @Operation(summary = "用户注册", description = "新用户注册账户")
    @PostMapping("/register")
    public Result<Void> register(@Parameter(description = "注册请求参数") @Validated @RequestBody RegisterRequest registerRequest,
                                 HttpServletRequest request) {
        log.info("收到用户注册请求，用户名: {}, 邮箱: {}",
                registerRequest.getUsername(), registerRequest.getEmail());

        // 验证验证码
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("captcha_code");
        String captchaCode = registerRequest.getCaptchaCode();

        if (sessionCode == null || !sessionCode.equalsIgnoreCase(captchaCode)) {
            log.warn("注册失败，验证码错误，用户名: {}", registerRequest.getUsername());
            return Result.error(400, "验证码错误");
        }

        // 验证通过后移除验证码
        session.removeAttribute("captcha_code");

        authService.register(registerRequest);
        log.info("用户注册请求处理成功，用户名: {}", registerRequest.getUsername());
        return Result.success();
    }

    @Operation(summary = "用户登出", description = "用户退出登录")
    @PostMapping("/logout")
    public Result<Void> logout() {
        log.info("收到用户登出请求");
        authService.logout();
        log.info("用户登出请求处理成功");
        return Result.success();
    }

    @Operation(summary = "刷新Token", description = "使用刷新Token获取新的访问Token")
    @PostMapping("/refresh")
    public Result<LoginResponse> refreshToken(@Parameter(description = "HTTP请求对象") HttpServletRequest request) {
        log.debug("收到Token刷新请求");

        String refreshToken = extractTokenFromRequest(request);
        if (refreshToken == null) {
            return Result.error(400, "Token不能为空");
        }

        LoginResponse response = authService.refreshToken(refreshToken);
        log.info("Token刷新成功");
        return Result.success(response);
    }

    @Operation(summary = "获取当前用户信息", description = "获取当前登录用户的基本信息")
    @GetMapping("/current")
    public Result<User> getCurrentUser() {
        log.debug("收到获取当前用户信息请求");

        User currentUser = authService.getCurrentUser();
        if (currentUser != null) {
            log.debug("获取当前用户信息成功，用户ID: {}", currentUser.getId());
            return Result.success(currentUser);
        } else {
            log.warn("获取当前用户信息失败，用户未登录");
            return Result.error(401, "用户未登录");
        }
    }




    /**
     * 从请求中提取Token
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}